package com.ruoyi.project.system.controller

import com.ruoyi.common.constant.UserConstants
import com.ruoyi.framework.aspectj.lang.annotation.*
import com.ruoyi.framework.aspectj.lang.enums.BusinessType
import com.ruoyi.framework.web.controller.BaseController
import com.ruoyi.framework.web.domain.AjaxResult
import com.ruoyi.project.system.domain.SysDept
import com.ruoyi.project.system.service.ISysDeptService
import org.apache.commons.lang3.ArrayUtils
import org.apache.commons.lang3.StringUtils
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.security.access.prepost.PreAuthorize
import org.springframework.validation.annotation.Validated
import org.springframework.web.bind.annotation.*

/**
 * 部门信息
 *
 * @author ruoyi
 */
@RestController
@RequestMapping("/system/dept")
open class SysDeptController : BaseController() {
    @Autowired
    private val deptService: ISysDeptService? = null

    /**
     * 获取部门列表
     */
    @PreAuthorize("@ss.hasPermi('system:dept:list')")
    @GetMapping("/list")
    fun list(dept: SysDept?): AjaxResult {
        val depts = deptService!!.selectDeptList(dept)
        return AjaxResult.Companion.success(depts)
    }

    /**
     * 查询部门列表（排除节点）
     */
    @PreAuthorize("@ss.hasPermi('system:dept:list')")
    @GetMapping("/list/exclude/{deptId}")
    fun excludeChild(@PathVariable(value = "deptId", required = false) deptId: Long): AjaxResult {
        val depts = deptService!!.selectDeptList(SysDept())?.toMutableList()
        val it = depts!!.iterator()
        while (it.hasNext()) {
            val d = it.next() as SysDept
            if (d.deptId!!.toInt().toLong() == deptId
                    || ArrayUtils.contains(StringUtils.split(d.ancestors, ","), deptId.toString() + "")
            ) {
                it.remove()
            }
        }
        return AjaxResult.Companion.success(depts)
    }

    /**
     * 根据部门编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:dept:query')")
    @GetMapping(value = ["/{deptId}"])
    fun getInfo(@PathVariable deptId: Long?): AjaxResult {
        deptService!!.checkDeptDataScope(deptId)
        return AjaxResult.Companion.success(deptService.selectDeptById(deptId))
    }

    /**
     * 新增部门
     */
    @PreAuthorize("@ss.hasPermi('system:dept:add')")
    @Log(title = "部门管理", businessType = BusinessType.INSERT)
    @PostMapping
    fun add(@Validated @RequestBody dept: SysDept): AjaxResult {
        if (UserConstants.NOT_UNIQUE == deptService!!.checkDeptNameUnique(dept)) {
            return AjaxResult.Companion.error("新增部门'" + dept.deptName + "'失败，部门名称已存在")
        }
        dept.createBy = username
        return toAjax(deptService.insertDept(dept))
    }

    /**
     * 修改部门
     */
    @PreAuthorize("@ss.hasPermi('system:dept:edit')")
    @Log(title = "部门管理", businessType = BusinessType.UPDATE)
    @PutMapping
    fun edit(@Validated @RequestBody dept: SysDept): AjaxResult {
        val deptId = dept.deptId
        deptService!!.checkDeptDataScope(deptId)
        if (UserConstants.NOT_UNIQUE == deptService.checkDeptNameUnique(dept)) {
            return AjaxResult.Companion.error("修改部门'" + dept.deptName + "'失败，部门名称已存在")
        } else if (dept.parentId == deptId) {
            return AjaxResult.Companion.error("修改部门'" + dept.deptName + "'失败，上级部门不能是自己")
        } else if (StringUtils.equals(
                        UserConstants.DEPT_DISABLE,
                        dept.status
                ) && deptService.selectNormalChildrenDeptById(deptId) > 0
        ) {
            return AjaxResult.Companion.error("该部门包含未停用的子部门！")
        }
        dept.updateBy = username
        return toAjax(deptService.updateDept(dept))
    }

    /**
     * 删除部门
     */
    @PreAuthorize("@ss.hasPermi('system:dept:remove')")
    @Log(title = "部门管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{deptId}")
    fun remove(@PathVariable deptId: Long?): AjaxResult {
        if (deptService!!.hasChildByDeptId(deptId)) {
            return AjaxResult.Companion.error("存在下级部门,不允许删除")
        }
        if (deptService.checkDeptExistUser(deptId)) {
            return AjaxResult.Companion.error("部门存在用户,不允许删除")
        }
        deptService.checkDeptDataScope(deptId)
        return toAjax(deptService.deleteDeptById(deptId))
    }
}
